#!/usr/bin/env python3
"""
简化的服务器启动脚本
"""

import os
import sys
import subprocess
import time

def check_dependencies():
    """检查依赖是否安装"""
    required_packages = [
        'fastapi',
        'uvicorn',
        'langchain',
        'requests'
    ]
    
    missing = []
    for package in required_packages:
        try:
            __import__(package)
            print(f"✓ {package}")
        except ImportError:
            print(f"✗ {package}")
            missing.append(package)
    
    return missing

def install_missing_packages(packages):
    """安装缺失的包"""
    if packages:
        print(f"\n安装缺失的包: {', '.join(packages)}")
        cmd = [sys.executable, '-m', 'pip', 'install'] + packages
        subprocess.run(cmd, check=True)

def start_backend():
    """启动后端服务"""
    print("启动后端服务...")
    
    # 切换到backend目录
    os.chdir('backend')
    
    # 启动uvicorn服务器
    cmd = [
        sys.executable, '-m', 'uvicorn', 
        'app.main:app', 
        '--host', '0.0.0.0', 
        '--port', '8000',
        '--reload'
    ]
    
    try:
        subprocess.run(cmd)
    except KeyboardInterrupt:
        print("\n服务器已停止")
    except Exception as e:
        print(f"启动失败: {e}")

def main():
    """主函数"""
    print("=== 论文搜索引擎服务器启动 ===\n")
    
    # 检查依赖
    print("检查Python依赖...")
    missing = check_dependencies()
    
    if missing:
        try:
            install_missing_packages(missing)
            print("依赖安装完成！")
        except Exception as e:
            print(f"依赖安装失败: {e}")
            return
    
    print("\n所有依赖已就绪！")
    
    # 显示访问信息
    print("\n=== 服务访问信息 ===")
    print("前端界面: 已在浏览器中打开 frontend/index.html")
    print("后端API: http://localhost:8000")
    print("API文档: http://localhost:8000/docs")
    print("健康检查: http://localhost:8000/health")
    
    print("\n按 Ctrl+C 停止服务器")
    print("=" * 50)
    
    # 启动后端
    start_backend()

if __name__ == "__main__":
    main()